package com.rzhkj.box.ctrl;

import com.alibaba.fastjson.JSON;
import com.rzhkj.box.entity.Box;
import com.rzhkj.box.entity.BoxFile;
import com.rzhkj.box.entity.MediaType;
import com.rzhkj.box.service.BoxSV;
import com.rzhkj.box.service.DocSV;
import com.rzhkj.core.base.BaseCtrl;
import com.rzhkj.core.base.JwtToken;
import com.rzhkj.core.common.Constants;
import com.rzhkj.core.entity.BeanRet;
import com.rzhkj.core.exceptions.BaseException;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Controller
@RequestMapping("/form")
@Api(value = "文件上传", description = "文件上传")
@Slf4j
public class FormUploadCtrl extends BaseCtrl {

    @Resource
    private DocSV docSV;
    @Resource
    private BoxSV boxSV;


    /***
     * 上传图片 仅支持文件流上传方式
     * {
     *  "isCache":"True/False 可选",
     *  "isCover":"True/False 可选",
     *  "size":520,
     *  "mediaType":"JPG",
     *  "file":"base64 code",
     *  "namespace":"路径空间 可选",
     *  "customFileName":"自定义名称 可选",
     *  "compressType":"压缩类型 可选",
     *  "notifyUrl":"回调通知路径 可选",
     *  "notifyData":"回调传递数据 可选 {"size":"${size}","path":"${path}","a":"a","b":"b"}",
     *  "notifyContentType":"回传数据类型:Content-Type 可选"
     * }
     *
     * 1.获取密文，并解密获得apikey，利用apikey判断是否有权限上传
     * 2.解密的数据进行对象转化，并进行上传
     *
     * @return BeanRet
     */
    @ApiOperation(value = "上传图片 仅支持文件流上传方式", notes = "上传图片 仅支持文件流上传方式，接口接收的是springmvc的文件mulpartfile类，请注意这个特性，并且是一个单文件模式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "jwt 的加密内容", paramType = "query")
    })
    @PostMapping("/upload")
    @ResponseBody
    public BeanRet upload(String data, @ApiParam(value = "上传文件", required = true) MultipartFile file) throws Exception {
        //1.获取密文，并解密获得apikey，利用apikey判断是否有权限上传
        String apiKey = request.getHeader(Constants.ApiKey.val.toString());//从header中获取apiKey
        Assert.hasText(apiKey, BaseException.BaseExceptionEnum.Ilegal_Param.name());
        Map<String, Object> param = new HashMap<>();
        param.put("apiKey", apiKey);
        Box box = boxSV.load(param);
        if (box == null) {
            return BeanRet.create();
        }
        JwtToken jwtToken = new JwtToken()
                .secret(box.getApiSecret())
                .token(data);

        boolean verify = jwtToken.verifier();
        if (!verify) {
            return BeanRet.create();
        }

        String json = jwtToken.getTokenValue(Constants.Content.val.toString());
        if (json == null) {
            return BeanRet.create();
        }
        log.debug(json);

        //2.解密的数据进行对象转化，并进行上传
        BoxFile boxFile = JSON.parseObject(json, BoxFile.class);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
        boolean flag = false;
        MediaType mediaType = MediaType.getEnum(boxFile.getMediaType());

        if (mediaType == MediaType.AllImage || mediaType == MediaType.GIF
                || mediaType == MediaType.PNG || mediaType == MediaType.JPG
                || mediaType == MediaType.ICO || mediaType == MediaType.BMP) {
            flag = docSV.uploadPic(boxFile, box.getCode(), file.getInputStream(), suffix, file.getSize());
        } else {
            flag = docSV.uploadDoc(boxFile, box.getCode(), file.getInputStream(), suffix, file.getSize());
        }

        return BeanRet.create(flag, "");
    }
}
